package com.kl.convert;

import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import org.junit.Test;

import java.io.File;
import java.io.IOException;

public class ConvertTest {

    /**
     * 将xml数据反序列化为bean对象
     * 这里的xml数据和bean对象中的属性值大小写不对应
     * 通过@JsonProperty将bean对象和xml数据一一对应
     */
    @Test
    public void test1() throws IOException {
        XmlMapper xmlMapper = new XmlMapper();
        String xmlContent = "<SimpleBeanForCapitalizedFields>\n" +
                "    <X>1</X>\n" +
                "    <y>2</y>\n" +
                "</SimpleBeanForCapitalizedFields>\n";
        SimpleBeanForCapitalizedFields value
                = xmlMapper.readValue(xmlContent, SimpleBeanForCapitalizedFields.class);
        System.out.println(value);
    }

    /**
     * 将bean对象序列号为xml数据并存储到指定路径
     * 通过增加注解@JsonProperty，可以正确序列化java对象至包括大写元素的xml字符串
     */
    @Test
    public void test2()
            throws IOException {
        XmlMapper xmlMapper = new XmlMapper();
        xmlMapper.writeValue(new File("src/main/java/com/kl/convert/simple_bean_capitalized.xml"),
                new SimpleBeanForCapitalizedFields());
        File file = new File("src/main/java/com/kl/convert/simple_bean_capitalized.xml");
        assertNotNull(file);
    }

    private void assertNotNull(Object obj) {
        if (obj == null){
            throw new NullPointerException("参数为空");
        }
    }

}
